/* 
计算拖动的rpx大小: (endTouches.pageX - startTouches.pageX) / screenRatio

*/
//上传图片的类型
const imgRatioArr = [
  { w: 1, h: 1, category: 1 },
  { w: 5, h: 3, category: 2 }
];
//rpx单位的计算尺寸
const windowWRPX = 750;
//设备参数
const systemInfo = wx.getSystemInfoSync();
//设备分辩率
const pixelRatio = systemInfo.pixelRatio;
//rpx 和 px单位的转换比
const screenRatio = systemInfo.screenWidth / windowWRPX;
const app = getApp();
Page({
  data: {
    animationData: {},//拖动裁剪框的动画效果
    returnImage: '',//返回图片的路径
    isShowImg: false,//是否显示图片
    // 初始化的宽高
    cropperInitW: windowWRPX,
    cropperInitH: windowWRPX,
    // 动态的宽高
    cropperW: 0,
    cropperH: 0,
    // 动态的left top值
    cropperL: 0,
    cropperT: 0,
    // 图片缩放值
    scaleP: 0,
    imageW: 0,
    imageH: 0,
    // 裁剪框 宽高
    cutW: 0,
    cutH: 0,
    cutL: 0,
    cutT: 0,
    imgUrl: ''//需要处理的图片
  },
  //临时的数据
  cData: {
    dragX: 0,//裁剪框的左位移
    dragY: 0,//裁剪框的上位移
    dragStartTouches: null,//改变剪切框大小的初始坐标
    startTouches: null,//改变剪切框位置的初始坐标
    animation: null,//改变剪切框位置的动画
  },
  onLoad: function (options) {
    //这个是临时测试数据，可删除
    console.log(options);
    // if(!options){
    //   options = {};
    //   options.cutType = 0;
    //   options.imgfile = 'http://tmp/wx01d45375aedb0d64.o6zAJs5NnjT7-T6G3vTANweP_2OE.70ccb5880731c6e76a9b27c75837475e.jpg'
    // }
    this.cData.animation = wx.createAnimation({
      duration: 0,
      timingFunction: 'ease',
    });
    var setting = JSON.parse(options.setting);
    this.setData({
      imgUrl: options.imgfile,
      setting:setting,
      imgRatio: imgRatioArr[setting.cuttype],
    })
    this.initImg();
  },
  //初始化图片信息
  initImg() {
    var _this = this,
      imgUrl = _this.data.imgUrl,
      imgRatio = _this.data.imgRatio;
    wx.showLoading({
      title: '图片加载中...',
    })
    wx.getImageInfo({
      src: imgUrl,
      success: function success(res) {
        var innerRatio = res.width / res.height,
          scaleP = res.width * pixelRatio / windowWRPX,
          //图片原始高宽
          imageW = res.width * pixelRatio,
          imageH = res.height * pixelRatio,
          //显示的图片高宽
          cropperW,
          cropperH,
          //显示的图片left和top
          cropperL,
          cropperT,
          //显示的裁剪框高、宽、left、top
          cutW,
          cutH,
          cutL,
          cutT;
        if (innerRatio >= 1) {
          cropperW = windowWRPX;
          cropperH = windowWRPX / innerRatio;
          cropperL = 0;
          cropperT = Math.ceil((windowWRPX - cropperH) / 2);
          cutH = Math.ceil(cropperH / 2);
          cutW = Math.ceil(cutH * imgRatio.w / imgRatio.h);
        } else {
          cropperW = windowWRPX * innerRatio;
          cropperH = windowWRPX;
          cropperL = Math.ceil((windowWRPX - cropperW) / 2);
          cropperT = 0;
          cutW = Math.ceil(cropperW / 2);
          cutH = Math.ceil(cutW * imgRatio.h / imgRatio.w);
        }
        cutT = Math.ceil((cropperH - cutH) / 2);
        cutL = Math.ceil((cropperW - cutW) / 2);

        _this.setData({
          cropperW: cropperW,
          cropperH: cropperH,
          cropperL: cropperL,
          cropperT: cropperT,
          cutW: cutW,
          cutH: cutH,
          cutL: cutL,
          cutT: cutT,
          scaleP: scaleP,
          imageW: imageW,
          imageH: imageH,
          isShowImg: true
        });
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  // 拖动裁剪框开始
  contentStartMove(e) {
    this.cData.startTouches = e.touches[0];
  },

  // 拖动裁剪框移动
  contentMoveing(e) {
    var _this = this,
      animation = _this.cData.animation,
      startTouches = _this.cData.startTouches,
      endTouches = e.touches[0],
      dragLengthX = (endTouches.pageX - startTouches.pageX) / screenRatio,
      dragLengthY = (endTouches.pageY - startTouches.pageY) / screenRatio;
    dragLengthX = _this.getRealLeft(dragLengthX);
    dragLengthY = _this.getRealTop(dragLengthY);
    this.cData.dragX = dragLengthX;
    this.cData.dragY = dragLengthY;
    animation.translate(dragLengthX, dragLengthY).step();
    this.setData({
      animationData: animation.export()
    });
  },
  //拖动裁剪框结束
  contentEndMove(e) {
    var _this = this,
      animation = _this.cData.animation,
      startTouches = this.cData.startTouches;
    //改变裁剪框大小时，事件会冒泡到这儿，可以通过这个参数判断是否是冒泡
    if (!startTouches) return;
    this.cData.startTouches = null;
    animation.translate(0, 0).step();
    _this.setData({
      cutL: _this.data.cutL + _this.cData.dragX / screenRatio,
      cutT: _this.data.cutT + _this.cData.dragY / screenRatio,
      animationData: animation.export(),
    })
  },
  // 获取图片
  getImageInfo() {
    var _this = this;
    wx.showLoading({
      title: '图片生成中...',
    })
    const ctx = wx.createCanvasContext('myCanvas')
    ctx.drawImage(_this.data.imgUrl)
    ctx.draw(false, _this.drawCallFn);//这儿的回调是1.7.0版本以上才支持的 
    /*wx.downloadFile({
      //图片下载才需要此方法
      url: _this.data.imgUrl, //仅为示例，并非真实的资源
      success: function (res) {
        
      },
      complete:function(){
        console.warn('downloadFile-complete', arguments);
      },
    });*/
  },
  //图片绘制完成的回调 真正的裁剪
  drawCallFn() {
    console.warn('drawCallFn', arguments);
    var _this = this;
    var canvasW = _this.data.cutW / _this.data.cropperW * _this.data.imageW / pixelRatio
    var canvasH = _this.data.cutH / _this.data.cropperH * _this.data.imageH / pixelRatio
    var canvasL = _this.data.cutL / _this.data.cropperW * _this.data.imageW / pixelRatio
    var canvasT = _this.data.cutT / _this.data.cropperH * _this.data.imageH / pixelRatio
    wx.canvasToTempFilePath({
      x: canvasL,
      y: canvasT,
      width: canvasW,
      height: canvasH,
      destWidth: canvasW,
      destHeight: canvasH,
      canvasId: 'myCanvas',
      success: function (res) {
        var tempFilePath = res.tempFilePath;
        _this.fileUpload(tempFilePath);
      },
      complete: function () {
        console.warn('canvasToTempFilePath-complete', arguments);
      }
    });
  },
  //上传到服务器
  fileUpload(tempFilePath) {
    var _this = this,
      imgRatio = _this.data.imgRatio;
    var setting = _this.data.setting;
    wx.uploadFile({
      url: app.globalData.UploadUrl,
      filePath: tempFilePath,
      name: 'file',
      formData: setting.param,
      success: function (res) {
        wx.hideLoading();
        var data = JSON.parse(res.data);
        app.globalData.tempUrl = data.data;
        let pages = getCurrentPages();//当前页面
        let prevPage = pages[pages.length - 3];//上上一页面
        prevPage.setData({
            FilePaths: data.data
        });
        wx.navigateBack({
          delta: 2
        });
      },
      complete: function () {
        console.warn('uploadFile-complete', arguments);
      },
    });
  },
  // 设置大小的时候触发的touchStart事件
  dragStart(e) {
    this.cData.dragStartTouches = e.touches[0];
  },

  // 设置大小的时候触发的touchMove事件
  dragMove(e) {
    var _this = this,
      dragStartTouches = _this.cData.dragStartTouches,
      dragEndTouches = e.touches[0],
      imgRatio = _this.data.imgRatio,
      dragType = e.target.dataset.drag;
    _this.cData.dragStartTouches = dragEndTouches;
    switch (dragType) {
      case 'right':
      case 'left':
        var isLeft = dragType == 'left',
          dragLength = (dragEndTouches.pageX - dragStartTouches.pageX) / screenRatio,
          newW = _this.data.cutW + (isLeft ? - dragLength : dragLength),
          newH = newW * imgRatio.h / imgRatio.w,
          newL = isLeft ? _this.data.cutL + dragLength : _this.data.cutL;
        if (newL < 0) {
          newL = 0;
        }
        if (newW < 50 || newH < 50) {
          return;
        }
        if (_this.data.cropperW - newL - newW < 0) {
          return;
        }
        if (_this.data.cropperH - _this.data.cutT - newH < 0) {
          return;
        }
        var obj = {};
        obj.cutW = newW;
        obj.cutH = newH;
        if (isLeft) {
          obj.cutL = newL;
        }
        _this.setData(obj);
        break;
      case 'top':
      case 'bottom':
        var isTop = dragType == 'top',
          dragLength = (dragEndTouches.pageY - dragStartTouches.pageY) / screenRatio,
          newH = _this.data.cutH + (isTop ? - dragLength : dragLength),
          newW = newH * imgRatio.w / imgRatio.h,
          newT = isTop ? _this.data.cutT + dragLength : _this.data.cutT;
        if (newT < 0) {
          newT = 0;
        }
        if (newW < 50 || newH < 50) {
          return;
        }
        if (_this.data.cropperW - _this.data.cutL - newW < 0) {
          return;
        }
        if (_this.data.cropperH - newT - newH < 0) {
          return;
        }
        var obj = {};
        obj.cutW = newW;
        obj.cutH = newH;
        if (isTop) {
          obj.cutT = newT;
        }
        _this.setData(obj);
        break;
    }
  },
  getRealLeft(dragLengthX) {
    var _this = this,
      minX = -_this.data.cutL * screenRatio,
      maxX = (_this.data.cropperW - _this.data.cutL - _this.data.cutW) * screenRatio;
    if (dragLengthX < minX) {
      dragLengthX = minX;
    } else if (dragLengthX > maxX) {
      dragLengthX = maxX;
    }
    return dragLengthX;
  },
  getRealTop(dragLengthY) {
    var _this = this,
      minY = -_this.data.cutT * screenRatio,
      maxY = (_this.data.cropperH - _this.data.cutT - _this.data.cutH) * screenRatio;
    if (dragLengthY < minY) {
      dragLengthY = minY;
    } else if (dragLengthY > maxY) {
      dragLengthY = maxY;
    }
    return dragLengthY;
  }
})